package fr.pud.client.controller;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import fr.pud.client.model.Route;
import fr.pud.client.model.Routes;
import fr.pud.client.view.MapRoute;
import fr.pud.client.view.MapRoutes;
import fr.pud.utils.Tools;

/**
 * An observer which observes the model and updates the view.
 * Apr 9, 2012 - OSE.
 * @author Simon Devineau, Adrien Hierry, Leopold Houdin, Pierre Reliquet
 *         Ecole des Mines de Nantes
 *         ModelObserver.java
 */
public class ModelObserver implements Observer {
    /**
     * The singleton.
     */
    private static ModelObserver instance = null;

    /**
     * @return the singleton
     */
    public static ModelObserver getInstance() {
        if (instance == null) {
            instance = new ModelObserver();
        }
        return instance;
    }

    /**
     * The index of the color chosen.
     */
    private int chooseColors = 0;

    /**
     * A private constructor to respect the singleton.
     */
    private ModelObserver() {
    }

    /**
     * If the model is modified (routes) it updates the view (MapRoutes).
     */
    @Override
    public void update(Observable arg0, Object arg1) {
        Color c = Tools.COLORS[this.chooseColors];
        if (arg1 instanceof Integer) {
            Integer i = (Integer) arg1;
            MapRoutes.getInstance().setMapRoute(
                    i,
                    ((ArrayList<Route>) Routes.getInstance().getRoutes())
                            .get(i), c);
        }
        if (arg1 instanceof Route) {
            MapRoute mapRoute = new MapRoute((Route) arg1,
                    ((Route) arg1).getVehicle(), c);
            MapRoutes.getInstance().add(mapRoute);
        }
        this.chooseColors = (this.chooseColors + 1) % Tools.COLORS.length;
    }
}
